import {Button, Input, message, Popconfirm, Select, Switch} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {queryRule,queryStore,addCents,centsStores,centsDetail} from './service';

import styles from "@/global.less";

import Access from '@/components/Access/Access';
import CreateForm from "./components/CreateForm";
import EditTableStore from "@/pages/PositionManagement/components/EditTableStore";

import {CloseOutlined} from "@ant-design/icons";
import OrderCommon from "@/pages/OrderCommon";
import {getPayOrder} from "@/pages/VipManagement/IntegralDay/service";
import Moment from "moment";

const TableList = (props) => {
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [detailsCount, setDetailsCount] = useState();
  const [createModalVisible, handleModalVisible] = useState(false);
  const [detailsModalVisible, handleDetailsVisible] = useState(false);
  const [storeArr, setStoreArr] = useState([]);
  const [children, setChildren] = useState([]);
  const [selected, setSelected] = useState([]);
  const [storeValue, setStoreValue] = useState([]);
  const [record, setRecord] = useState({});
  const [tableLoading, setTableLoading] = useState(false);
  const [order, setOrder] = useState(false);
  const [payOrderValues, setPayOrderValues] = useState({});
  useEffect(() => {
    getStore();
  }, []);
  const handlePay = (params) => {
    getPayOrder(params).then((res) => {
      const {code, data} = res;
      (code === 0 && data) ? (setPayOrderValues(data), setOrder(true)) : null;
    });
  };
  const getStore = () => {
    setTableLoading(true);
    queryStore()
      .then((res) => {
        const {code} = res;
        if (code === 0){
          setStoreArr(res.data);
          setTableLoading(false);
          actionRef.current.reload();
        }else{
          message.info(res.message);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const details = [
    {
      title: '账期',
      dataIndex: 'dataTime',
      hideInSearch: true,
      width: 120,
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '当期销售总额',
      dataIndex: 'totalAmount',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '当期已分账总额',
      dataIndex: 'centsMoney',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '当期未分账总额',
      dataIndex: 'undisMoney',
      hideInSearch: true,
      width: 120,
    },
  ];
  const columns = [
    {
      title: '分账接收方',
      dataIndex: 'centsName',
      hideInSearch: true,
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '商户号',
      dataIndex: 'mchId',
      hideInSearch: true,
    },
    {
      title: '总销售金额',
      dataIndex: 'totalAmount',
      hideInSearch: true,
    },
    {
      title: '已分账金额',
      dataIndex: 'payMoney',
      hideInSearch: true,
    },
    {
      title: '待分账金额',
      dataIndex: 'centsMoney',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '停用',
          status: 'error',
        },
        1: {
          text: '启用',
          status: 'Success',
        },
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        false: {
          text: '消费',
          status: 'error',
        },
        true: {
          text: '余额',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      width: 80,
      valueType: 'option',
      render: (_, record) => (
        <>
          <div style={{
            display: "flex",
            overflow: "hidden"
          }}>
            <Button
              type="primary"
              onClick={() => {
                centsStores({
                  id:record.id
                }).then(res=>{
                  let centsStores =res.data;
                  if (centsStores && centsStores.length>0){
                    setChildren(centsStores);
                    let stores = storeArr.filter(data=>{
                      return centsStores.indexOf(data.id)!==-1
                    });
                    record.storeList = centsStores;
                    setSelected(stores);
                  }
                  setRecord(record);
                  handleModalVisible(true);
                })
              }}
            >
              修改
            </Button>
            <Button
              type="primary"
              style={{
                marginLeft: "10px"
              }}
              onClick={() => {
                setRecord(record);
                handleDetailsVisible(true);
              }}
            >
              查看明细
            </Button>

          </div>

        </>
      ),
    },
  ];
  const StoreSelect = (record, select, selectedRows) => {
    if (select){
      const list = [record.id];
      setChildren(list.concat(children));
      const selectList = [record];
      setSelected(selected.concat(selectList));
    }else{
      setChildren(children.filter(id=>id!==record.id));
      setSelected(selected.filter(data=>data.id!==record.id));
    }
  };
  const StoreSelectAll = (selected, selectedRows, changeRows) => {
    setChildren(selectedRows.map(record=>record.id))
    const list = [];
    setSelected(list.concat(selectedRows));
  };
  const handleCommissionChild = (value) => {
    const list = JSON.parse(JSON.stringify(storeValue));
    list.map((item) => {
      if (item.storeId === value.id) {
        if (value.id === item.storeId) {
          item.commission = value.commission;
        }
      }
    });
    selected.map((item) => {
      item.id === value.id
        ? ((item.commission = value.commission), (item.positionId = positionId))
        : null;
    });
    setStoreValue(list);
  };

  const centsColumns = [
    {
      title: '分账接收方',
      dataIndex: 'centsName',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '分账接收方名称为必填项',
          },
        ],
      },
    },
    {
      title: '商户号',
      dataIndex: 'mchId',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '商户号为必填项',
          },
        ],
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '停用',
          status: 'Success',
        },
        1: {
          text: '启用',
          status: 'Success',
        },

      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select defaultValue={defaultRender.status} placeholder="请选择状态" allowClear>
            <Select.Option value={0}>停用</Select.Option>
            <Select.Option value={1}>启用</Select.Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '状态为必填项',
          },
        ],
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        false: {
          text: '消费',
          status: 'Success',
        },
        true: {
          text: '余额',
          status: 'Success',
        },

      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select defaultValue={defaultRender.status} placeholder="请选择类型" allowClear>
            <Select.Option value={false}>消费</Select.Option>
            <Select.Option value={true}>余额</Select.Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '类型为必填项',
          },
        ],
      },
    },
    {
      title: '分账店铺',
      dataIndex: 'storeList',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <EditTableStore
            dataSource={storeArr}
            onSelect={StoreSelect}
            onSelectAll={StoreSelectAll}
            handleChildren={children}
            childrenCommission={handleCommissionChild}
            CommissionState={false}
          />
        );
      },
    },
    {
      title: '已选中店铺',
      dataIndex: 'selected',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <div className="selected_div">
            {selected.map((item, index) => {
              return (
                <div key={index} className="store_selected">
                  <span>{item.name}</span>
                  <Popconfirm
                    title="确定删除该店铺吗?"
                    onConfirm={() => {
                      const handleId = JSON.parse(JSON.stringify(children));
                      const list = JSON.parse(JSON.stringify(selected));
                      list.map((item_, index) => {
                        if (item.id === item_.id) {
                          return list.splice(index, 1);
                        }
                      });
                      handleId.map((item_, index) => {
                        if (item.id === item_) {
                          return handleId.splice(index, 1);
                        }
                      });
                      setSelected(list);
                      setChildren(handleId);
                    }}
                    okText="是"
                    cancelText="否"
                  >
                    <CloseOutlined style={{ color: 'red', cursor: 'pointer' }} />
                  </Popconfirm>
                </div>
              );
            })}
          </div>
        );
      },
    },
  ];

  const detailColumns = [
    {
      title: '分账金额',
      dataIndex: 'amount',
      width: 60,
    },
    {
      title: '分账状态',
      dataIndex: 'status',
      width: 60,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 60,
      fixed: 'right',
      render: (_, item) => {
        return (
          <>
            <a
              onClick={() => {
                handlePay(item.orderId);

              }}
            >
              查看订单详情
            </a>
          </>
        )
      }
    }
  ];

  const detailRender = (e) => {
    return <>
      <ProTable
        rowKey="id"
        scroll={{x: 1400}}
        bordered
        dataSource={e.details}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={detailColumns}
      />
    </>
  };

  return (
    <PageContainer>
      <ProTable
        headerTitle="分账列表"
        actionRef={actionRef}
        rowKey={(record) => record.id}
        scroll={{x: 1200}}
        bordered
        loading={tableLoading}
        search={false}
        onReset={() => {

        }}
        footer={() => {

        }}
        toolBarRender={() => [
          <Button  type="primary" onClick={() => {
            setRecord({});
            setSelected([]);
            setChildren([]);
            handleModalVisible(true);
          }}>
            添加分账接收方
          </Button>
        ]}
        request={(params, sorter, filter) => {

          return queryRule({...params, sorter, filter});
        }}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: true,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
      />
      <CreateForm
        title="新增接收方"
        width={800}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        btn_view={false}
      >
        <ProTable
          className={styles.formBottom}
          rowKey={(record) => record.id}
          onSubmit={async (value) => {
            if (record){
              value.id = record.id;
            }
            if (children){
              value.storeList = children;
            }
            addCents(value).then(res=>{
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            });
          }}
          bordered
          form={{
            initialValues: record,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 4 },
            wrapperCol: { span: 24 },
          }}
          type="form"
          columns={centsColumns}
        />
      </CreateForm>
      <CreateForm
        title="分账明细"
        width={1200}
        onCancel={() => handleDetailsVisible(false)}
        modalVisible={detailsModalVisible}
        btn_view={false}
      >
        <ProTable
          rowKey={(record) => record.id}
          scroll={{x: 1200}}
          bordered
          loading={tableLoading}
          search={false}
          footer={false}
          toolBarRender={false}
          request={(params, sorter, filter) => {
            params.centsId = record.id;
            return centsDetail({...params, sorter, filter});
          }}
          postData={(payload) => {
            const {list, total} = payload;
            setDetailsCount(total);
            return list || [];
          }}
          columns={details}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
            showTitle: false,
            total: detailsCount,
            showTotal: (total) => `共${total}条`,
          }}
          expandedRowRender={detailRender}
        />
      </CreateForm>
      <CreateForm
        title={'订单详情'}
        width={1300}
        onCancel={() => setOrder(false)}
        modalVisible={order}
      >
        <OrderCommon
          payOrderValues={payOrderValues}
          refund={false}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
